
#ifndef  PAGER_H
#define  PAGER_H

#include "common.h"

class Page;
class Cache;
/* 
 * Functions:
 *
 *  Only Module that access native file & journal
 *  Mapping random access/Bytes-oriented to random access/page-based
 *  Supply easy-to-use filesystem-independent interface for page-accessing from file
 *
 * No-support:
 *
 *   Neither interpreter the content of db
 *   Nor modify the content, (only change file header)
 */
class Pager {
public:
    Pager(const std::string & fileName, const int64_t cacheSize=0x400*0x400, const int32_t pageSize =0x400);
    virtual ~Pager();

    int open();
    void close();

    Page * allocPage(const PageNumberType pageNo);
    Page * acquirePage(const PageNumberType pageNo);
    int releasePage(Page * page);

    Page * readPage(const PageNumberType pageNo);
    int writePage(Page * page);

    int savePoint();
    
    const int32_t getPageSize() const { return pageSize; }
    const std::string toString() const;

private:
    int truncateFile(PageNumberType pageNo);
    int readFile(const PageNumberType pageNo, char * pageAddr, int length);
    int writeFile(const PageNumberType pageNo, char * pageAddr, int length);
    int assertFileExists();
    int seekToPage(const PageNumberType pageNo);
private:
    std::string fileName;
    const int32_t pageSize;

    std::fstream * file;
    Cache * cache;
    std::map<PageNumberType, Page *> dirtyMap;
};


#endif   /* PAGER_H */
